package main

import "fmt"

var l *Loop

func OnRead(s *Stream, n int, b []byte) {
	fmt.Println("Read")

	if b == nil {
		fmt.Println("Remote Close Socket")
		return
	}

	_, err := s.Write(b)
	if err != nil {
		panic(err)
	}
}

func OnConnect(s *Stream, err error) {
	if err != nil {
		panic(err)
	}

	fmt.Println("Connection")

	c := &TCP{}
	c.Init(l)

	if err := s.Accept(&c.Stream); err == nil {
		fmt.Println("ReadStart")
		c.ReadStart(OnRead)
	} else {
		panic(err)
	}
}

func main() {
	l = &Loop{}
	l.Init()

	t := &TCP{}
	t.Init(l)
	err := t.Listen("tcp4", "0.0.0.0:19771", 0, OnConnect)
	if err != nil {
		panic(err)
	}

	l.Start()
}
